package com.think.cloud.thinkshop.mall.service.payment.paypal.config;

import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import com.think.cloud.thinkshop.mall.domain.payment.PaymentConfig;
import com.think.cloud.thinkshop.mall.service.payment.IPaymentConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;

@Configuration
@EnableConfigurationProperties(PaypalProperties.class)
@Slf4j
public class PaypalConfig {
    @Autowired
    public PaypalProperties paypalProperties;
    @Autowired
    private IPaymentConfigService paymentConfigService;

    @Bean
    public APIContext apiContext() throws PayPalRESTException {
        PaymentConfig paymentConfig = paymentConfigService.selectPaymentConfigById(1L);
        if (Objects.isNull(paymentConfig)) {
            log.error("paypal 支付配置不存在");
        }
        APIContext apiContext = new APIContext();
        try {
            apiContext = new APIContext(paymentConfig.getClientId(), paymentConfig.getSecret(), paypalProperties.getMode());
            log.info("paypal 初始化成功");
        } catch (Exception e) {
            log.error("paypal 获取token失败", e);
        }
        return apiContext;
    }
}
